package com.example.zuoye1;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.List;

@WebServlet(name = "CartServlet",urlPatterns = "/CartServlet")
@WebServlet(name = "CartServlet", urlPatterns = "/CartServlet")
public class CartServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter out = resp.getWriter();
            // 变量cart引用用户的购物车
            List<Cake> cart = null;
            // 变量pruFlag标记用户是否买过商品
            boolean purFlag = true;
            // 获得用户的session
            HttpSession session = req.getSession(false);
            // 如果session为null，purFlag置为false
            if (session == null) {
                purFlag = false;
            } else {
                // 获得用户购物车
                cart = (List) session.getAttribute("cart");
                // 如果用的购物车为null，purFlag置为false
                if (cart == null) {
                    purFlag = false;
                }
            }
            /*
             * 如果purFlag为false，表明用户没有购买图书 重定向到ListServlet页面
             */
            if (!purFlag) {
                out.write("对不起！您还没有购买任何商品！<br>");
                List<Cake> cart = (List<Cake>) req.getSession().getAttribute("cart");

                out.println("<html>");
                out.println("<head><title>购物车</title></head>");
                out.println("<body>");
                if (cart == null || cart.isEmpty()) {
                    out.println("对不起！您还没有购买任何商品！");
                } else {
                    // 否则显示用户购买图书的信息
                    out.write("您购买的蛋糕有：<br>");
                    double price = 0;
                    out.println("您购买的蛋糕有：<br>");
                    out.println("<ul>");
                    for (Cake cake : cart) {
                        out.write(cake.getName() + "<br>");
                        out.println("<li>" + cake.getName() + " - 价格：" + cake.getPrice() + "</li>");
                    }
                    out.println("</ul>");
                }
                out.println("</body>");
                out.println("</html>");
                out.close();
            }
        }
\ No newline at end of file
    }